package edu.iscas.xcheck.analysis.dom.visitors;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import edu.iscas.xcheck.analysis.dom.model.DomNode;
import edu.iscas.xcheck.analysis.dom.utils.DomUtils;

public class ApproxMatchVisitor extends DomVisitor {
	DomNode ref;
	Map<String, String> matched;
	int cnt = 0;
	float bestMatchIdx;
	DomNode bestMatch;

	float THRESHOLD_GLOBAL = 0.85f;
	
	public ApproxMatchVisitor(DomNode node, Map<String, String> matched) {
//		System.out.println("processing "+node);
		ref = node;
		this.matched = matched;
		this.bestMatchIdx = 0;
		this.bestMatch = null;
	}

	@Override
	public void visit(DomNode node) {
		cnt++;
		
		if(!node.isMatched()) {
			if(StringUtils.equals(ref.getTagName(), node.getTagName())) {
				float matchIndex = DomUtils.calculateMatchIndex(ref, node);
				if(matchIndex > THRESHOLD_GLOBAL && matchIndex > bestMatchIdx) {
					bestMatchIdx = matchIndex;
					bestMatch = node;
				}
			}
		}
	}
	
	public DomNode matchPost() {
		if(bestMatch != null) {
			if(ref.getxPath().equals("/HTML/BODY/DIV[2]/DIV/DIV/DIV[4]/DIV[5]/DIV/DIV[2]/DIV/P")){
				System.out.println("Step 3: "+ref.getHash()+"="+bestMatch.getHash());
			}
			matched.put(ref.getHash(), bestMatch.getHash());
			ref.setMatched(true);
			bestMatch.setMatched(true);
		}
		return bestMatch;
	}
	
	@Override
	public String toString() {
		return "AMV visited #nodes:"+cnt;
	}



}
